#!/usr/bin/env python3

import json
import shutil
import sys
import tarfile
import tempfile
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path
from urllib.request import urlopen


def http_archive(cfg_file: str, output_dir: str):
    cfg_fpath: Path = Path(cfg_file)
    output_dpath: Path = Path(output_dir)
    url = json.loads(cfg_fpath.read_text())['url']

    if output_dpath.is_dir():
        shutil.rmtree(output_dir)
    with urlopen(url) as ifs, tempfile.TemporaryFile() as ofs:
        while True:
            recv = ifs.read(4096)
            if not recv:
                break
            ofs.write(recv)
        ofs.seek(0)
        with tarfile.open(fileobj=ofs) as tar:
            tar.extractall(output_dpath)
    output_dpath.joinpath('.http_archive.json').write_text(json.dumps(
        dict(url=url, download_time=datetime.now().isoformat()), indent=2))

    for path in output_dpath.glob('**/*'):
        if not path.is_file():
            continue
        path.chmod(0o400)
    return 0


def prepare_parser(parser: ArgumentParser):
    parser.add_argument('cfg_file')
    parser.add_argument('--output_dir', default='.')
    return parser


if __name__ == '__main__':
    sys.exit(http_archive(**vars(prepare_parser(ArgumentParser()).parse_args())))
